#coding:utf-8
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.shortcuts import render
#from models import node_info
from django.contrib.auth.decorators import login_required
from forms import AddForm
from models import domain_info


@login_required(login_url="/login/")
def domain_view(request):
    print request
    if request.method == 'POST':# 当提交表单时
        form_info = AddForm(request.POST) # form 包含提交的数据
        print form_info
        print request.POST
        if form_info.is_valid():# 如果提交的数据合法
            #form = form_info.cleaned_data
            form_data = form_info.cleaned_data
            form_data['cname_domain'] = form_data['domain_name'] + '.99.com'
            print form_data['cname_domain']
            form_info.save()
            return HttpResponseRedirect('/domain')
#        else:
#            return render(request,'',locals())
        #else:
        #    return render(request, 'node_view.html',locals()) #这里看下怎么抛错

    else:# 当正常访问时
        form_info = AddForm()
    #加载界面的时候请求一次

    domain_list = domain_info.objects.all()
#    domain_list = node_info.objects.all()
    return render(request, 'domain_view.html',locals())


@login_required(login_url="/login/")
def domain_mod(request,node_id):
    print request
    try:
        num = int(node_id)
    except ValueError:
        raise Http404
    if request.method == 'POST':# 当提交表单时
        domain = domain_info.objects.get(id=node_id) # form 包含提交的数据
        form = AddForm(request.POST,instance=domain)
        if form.is_valid():# 如果提交的数据合法
            #form = form_info.cleaned_data
            form.save()
            return HttpResponseRedirect('/node')
        #else:
        #    return render(request, 'node_view.html',locals()) #这里看下怎么抛错
    else:
        domain = domain_info.objects.get(id=node_id)
        form = AddForm(
            initial={'domain_name':domain.domain_name,'source_line':domain.source_line,'source_type':domain.source_type,}
        )
        #form = AddForm()
    return render(request, 'domain_modify.html',locals())

@login_required(login_url="/login/")
def domain_del(request,node_id):
    try:
        num = int(node_id)
    except ValueError:
        raise Http404
    node = domain_info.objects.get(id=num)
    node.delete()
    return HttpResponseRedirect('/domain/')